<?php
abstract class DataObject
{
    public function FromArray(array $array)
    {
        $fields = get_object_vars($this);
        foreach ($fields as $key => $value)
        {
            $underscoredKey = self::CamelCaseToUnderscore($key);
            if ( isset($array[$underscoredKey]) )
            {
                $this->$key = $array[$underscoredKey];
            }
        }
    }

    public function ToArray()
    {
        $fields = get_object_vars($this);
        $result = array();
        foreach ($fields as $key => $value)
        {
            $key = self::CamelCaseToUnderscore($key);
            $result[$key] = $value;
        }
        return $result;
    }

    /**
     * Translates a camel case string into a string with underscores (e.g. firstName - first_name)
     * @param string $str String in camel case format
     * @return string $str Translated into underscore format
     */
    private static function CamelCaseToUnderscore($str)
    {
        return strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $str));
    }
}
?>